package com.bright.ghj.overt.service.impl;

import com.bright.ghj.common.util.StringUtil;
import com.bright.ghj.overt.pojo.vo.SaveFileResultVO;
import com.bright.ghj.overt.service.StoreFileService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author hxj
 * @Date 2024/3/8 11:45
 * @Description
 */
@Component
@RequiredArgsConstructor
@Qualifier("fileSystemStoreFile")
@ConditionalOnProperty(name = "store.type", havingValue = "fileSystem", matchIfMissing = true)
public class FileSystemStoreFileServiceImpl implements StoreFileService {

    @Override
    public List<SaveFileResultVO> saveFile(List<MultipartFile> multipartFiles, String baseDir) throws IOException {
        List<SaveFileResultVO> saveFileResultVOS = new ArrayList<>();

        URL resource = ClassUtils.getDefaultClassLoader().getResource("static/uploads/" + baseDir);
        if (resource == null) {
            throw new RuntimeException(baseDir + "路径不存在！");
        }
        String path = resource.getPath();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = simpleDateFormat.format(new Date());
        File file = new File(path + format);
        if (!file.exists()) {
            file.mkdirs();
        }

        for (MultipartFile multipartFile : multipartFiles) {

            String uuid = UUID.randomUUID().toString();
            String newFileName = uuid + "_" + multipartFile.getOriginalFilename();

            multipartFile.transferTo(new File(file, newFileName));

            SaveFileResultVO saveFileResultVO = new SaveFileResultVO();
            saveFileResultVO.setNewFileName(newFileName);
            saveFileResultVO.setUploadPath(StringUtil.replace(StringUtil.substringAfter(file.getPath(), "static"), "\\", "/") + "/");
            saveFileResultVO.setOldFileName(multipartFile.getOriginalFilename());

            saveFileResultVOS.add(saveFileResultVO);
        }
        return saveFileResultVOS;
    }

}
